import React, { useState, useEffect, useRef } from 'react';
import styled from 'styled-components';

// 样式定义
const Container = styled.div`
  text-align: center;
  padding: 20px;
  margin: 20px auto;
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
`;

const TimerDisplay = styled.div<{ time: number }>`
  font-size: 3rem;
  font-weight: bold;
  margin: 20px 0;
  color: ${props => props.time <= 10 ? 'red' : '#333'};
  transition: color 0.5s;
`;

const ButtonGroup = styled.div`
  display: flex;
  justify-content: center;
  gap: 10px;
`;

const Button = styled.button<{ $primary?: boolean; $secondary?: boolean }>`
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background-color: ${props => {
        if (props.$primary) return '#4CAF50';
        if (props.$secondary) return '#FFC107';
        return '#f0f0f0';
    }};
  color: ${props => props.$secondary ? '#333' : 'white'};
  
  &:hover {
    opacity: 0.9;
  }
`;

interface SimpleCountdownTimerProps {
    initialTime?: number;
}

const SimpleCountdownTimer: React.FC<SimpleCountdownTimerProps> = ({ initialTime = 60 }) => {
    const [time, setTime] = useState<number>(initialTime);
    const [isActive, setIsActive] = useState<boolean>(false);
    const intervalRef = useRef(0);

    useEffect(() => {
        if (isActive && time > 0) {
            intervalRef.current = setInterval(() => {
                setTime(prevTime => prevTime - 1);
            }, 1000);
        } else if (time === 0) {
            setIsActive(false);
        }

        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, [isActive, time]);

    const startTimer = (): void => {
        setIsActive(true);
    };


    const pauseTimer = (): void => {
        setIsActive(false);
    };

    const resetTimer = (): void => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }
        setTime(initialTime);
        setIsActive(false);
    };

    return (
        <Container>
            <h3>倒计时</h3>
            <TimerDisplay time={time}>{time}</TimerDisplay>
            <ButtonGroup>
                {isActive ? (
                    <Button $primary={false} $secondary={true} onClick={pauseTimer}>暂停</Button>
                ) : (
                    <Button $primary onClick={startTimer}>
                        {time === 0 ? '重新开始' : '开始'}
                    </Button>
                )}
                <Button onClick={resetTimer}>重置</Button>
            </ButtonGroup>
        </Container>
    );
};

export default SimpleCountdownTimer;
